package org.example;

import com.wechat.pay.java.core.util.PemUtil;
import okhttp3.HttpUrl;

import java.security.Signature;
import java.util.Base64;

/**
 * @author Tang
 * @classname SignUtils
 * @description [ 账单签名 ]
 * @date 2024/3/8 14:48
 */
public class SignUtils {
    /** 商户号 */
    public static String merchantId = "1593191541";
    /** 商户API私钥路径 */
    public static String privateKeyPath = "/Users/tanglonglong/IdeaProjects/wx-pay/cert/apiclient_key.pem";
    /** 商户证书序列号 */
    public static String merchantSerialNumber = "73AAF1F8897D4ECE9C6A468D2621410D2BADAF2A";
    /**
     * 自定义nonce
     */
    public static String nonceStr = "593BEC0C930BF1AFEB40B4A08C8FB242";

    private static String schema = "WECHATPAY2-SHA256-RSA2048";

    // Authorization: <schema> <token>
    // GET - getToken("GET", httpurl, "")
    // POST - getToken("POST", httpurl, json)

    public static void main(String[] args) throws Exception{
        String url = "https://api.mch.weixin.qq.com/v3/billdownload/file?token=cfA-3Uig0g3B_UQs7S6BFyoUaremBWJDPtg9emfMOovfEb-ZymeGZa5jzVpViqeE";
        String sign = getSign(url, "GET", "");
    }

    public static String getSign(String url,String method,String body) throws Exception{
        return getToken(method, url, body);
    }

    private static String getToken(String method, String url, String body) throws Exception{
        long timestamp = System.currentTimeMillis() / 1000;
        String message = buildMessage(method, HttpUrl.parse(url), timestamp, nonceStr, body);
        String signature = sign(message.getBytes("utf-8"));

        return schema + " mchid=\"" + merchantId + "\","
                + "nonce_str=\"" + nonceStr + "\","
                + "timestamp=\"" + timestamp + "\","
                + "serial_no=\"" + merchantSerialNumber + "\","
                + "signature=\"" + signature + "\"";
    }

    private static String sign(byte[] message) throws Exception{
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(PemUtil.loadPrivateKeyFromPath(privateKeyPath));
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }

    private static String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
        String canonicalUrl = url.encodedPath();
        if (url.encodedQuery() != null) {
            canonicalUrl += "?" + url.encodedQuery();
        }
        return method + "\n"
                + canonicalUrl + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + body + "\n";
    }


}
